package com.beerandjesus.sportofkings.handicapper.dao;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 * Date: Sep 8, 2012
 * Time: 5:01:41 PM
 */
public abstract class AbstractHibernateDAO implements AbstractDAO {

    private SessionFactory sessionFactory;

    protected Session getSession() {
        return getSessionFactory().getCurrentSession();
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    protected void dropAndCreate(String dropStatement, String createStatement, Logger log) {
        try {
            executeUpdate(dropStatement);
        } catch (HibernateException e) {
            log.warn("Error dropping table: " + e.getMessage());
            log.debug("Table drop error", e);
        }
        executeUpdate(createStatement);
    }

    protected void executeUpdate(String sqlQuery) {
        SQLQuery q;
        q = getSession().createSQLQuery(sqlQuery);
        q.executeUpdate();
    }
}
